package org.springside.examples.showcase.utilities.wb;

/**
 * http://www.cnblogs.com/beijia/archive/2011/11/22/62ToInt.html <br>
 * 将mid转换成短链
 * 
 * @author zhang.youlei@gmail.com
 * 
 */
public class SinaMid2Url {
	public static final String[] str62keys = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
			"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

	public static void main(String[] args) {
		// System.out.println(mid2url("3488655903078175"));
		// System.out.println(url2mid("yfyF50ONj"));
		System.out.println(url2mid("yB7fXogRL"));
	}

	/**
	 * mid转换为URL字符
	 * 
	 * @param mid 微博mid，如 "201110410216293360"
	 * @return 微博URL字符，如 "wr4mOFqpbO"
	 */
	public static String mid2url(String mid) {
		String url = "";
		for (int i = mid.length() - 7; i > -7; i = i - 7) {// 从最后往前以7字节为一组读取mid
			int offset1 = i < 0 ? 0 : i;
			int offset2 = i + 7;
			String num = mid.substring(offset1, offset2);
			String str = int10to62(new Integer(num).intValue());
			if (offset1 > 0) {// renjian@20120423 若不是第一组，则不足4位补0
				while (str.length() < 4) {
					str = '0' + str;
				}
			}
			url = str + url;
		}
		return url;
	}

	/**
	 * URL字符转换为mid
	 * 
	 * @param {String} url 微博URL字符，如 "wr4mOFqpbO"
	 * @return {String} 微博mid，如 "201110410216293360"
	 */
	public static String url2mid(String url) {
		String mid = "";
		for (int i = url.length() - 4; i > -4; i = i - 4) {// 从最后往前以4字节为一组读取URL字符
			int offset1 = i < 0 ? 0 : i;
			int offset2 = i + 4;
			String str = url.substring(offset1, offset2);
			str = str62to10(str);
			if (offset1 > 0) {// 若不是第一组，则不足7位补0
				while (str.length() < 7) {
					str = '0' + str;
				}
			}
			mid = str + mid;
		}
		return mid;
	}

	/**
	 * 62进制值转换为10进制
	 * 
	 * @param {String} str62 62进制值
	 * @return {String} 10进制值
	 */
	public static String str62to10(String str62) {
		long i10 = 0;
		for (int i = 0; i < str62.length(); i++) {
			int n = str62.length() - i - 1;
			String s = str62.substring(i, i + 1);
			int pos = 0;
			for (int j = 0; j < 62; j++) {
				if (str62keys[j].equals(s)) {
					pos = j;
					break;
				}
			}
			i10 += pos * Math.pow(62, n);
		}
		return i10 + "";
	}

	/**
	 * 10进制值转换为62进制
	 * 
	 * @param {String} int10 10进制值
	 * @return {String} 62进制值
	 */
	public static String int10to62(double int10) {
		String s62 = "";
		int r = 0;
		while (int10 != 0) {
			r = (int) (int10 % 62);
			s62 = str62keys[r] + s62;
			int10 = Math.floor(int10 / 62);
		}
		return s62;
	}

}
